'use strict'
const express = require('express'),
    router = express.Router(),
    User = require('../models/User.js'),
    Category = require('../models/Category.js'),
    Content = require('../models/Content.js')

router.use((req, res, next) => {
    if (!req.userInfo.isAdmin) {
        res.send('对不起，只有管理员才可以进入后台管理!')
        return
    }
    next()
})
router.get('/', (req, res, next) => {
    res.render('admin/index', {
        userInfo: req.userInfo
    })
})

router.get('/user', (req, res, next) => {

    let page = Number(req.query.page) || 1,
        limit = 10,
        pages = 0

    User.count().then((count) => {

        pages = Math.ceil(count / limit)
        page = Math.min(page, pages)
        page = Math.max(page, 1)

        let skip = (page - 1) * limit

        User.find().limit(limit).skip(skip).then((users) => {
            res.render('admin/user_index', {
                userInfo: req.userInfo,
                users,

                count,
                page,
                pages,
                limit
            })
        })

    })




})

router.get('/category', (req, res, next) => {
    let page = Number(req.query.page) || 1,
        limit = 10,
        pages = 0

    Category.count().then((count) => {

        pages = Math.ceil(count / limit)
        page = Math.min(page, pages)
        page = Math.max(page, 1)

        let skip = (page - 1) * limit

        Category.find().sort({
            _id: -1
        }).limit(limit).skip(skip).then((categories) => {
            res.render('admin/category_index', {
                userInfo: req.userInfo,
                categories,

                count,
                page,
                pages,
                limit
            })
        })

    })
})

router.get('/category/add', (req, res, next) => {
    res.render('admin/category_add', {
        userInfo: req.userInfo
    })
})

router.post('/category/add', (req, res, next) => {
    const name = req.body.name || ''
    if (name == '') {
        res.render('admin/error', {
            userInfo: req.userInfo,
            message: '名称不能为空'
        })
        return
    }

    Category.findOne({
        name: name
    }).then(rs => {
        if (rs) {
            res.render('admin/error', {
                userInfo: req.userInfo,
                message: '分类已经存在了'
            })
            return Promise.reject()
        } else {
            return new Category({
                name: name
            }).save()
        }
    }).then((newCategory) => {
        res.render('admin/success', {
            userInfo: req.userInfo,
            message: '分类增加成功',
            url: '/admin/category'
        })
    })
})

router.get('/category/edit', (req, res, next) => {
    const id = req.query.id || ''
    Category.findOne({
        _id: id
    }).then((category) => {
        if (!category) {
            res.render('admin/error', {
                userInfo: req.userInfo,
                message: '分类信息不存在'
            })
            return Promise.reject()
        } else
            res.render('admin/category_edit', {
                userInfo: req.userInfo,
                category
            })
    })
})

router.post('/category/edit', (req, res, next) => {
    const id = req.query.id || '',
        name = req.body.name
    Category.findOne({
        _id: id
    }).then((category) => {
        if (!category) {
            res.render('admin/error', {
                userInfo: req.userInfo,
                message: '分类信息不存在'
            })
        } else {
            if (name == category.name) {
                res.render('admin/success', {
                    userInfo: req.userInfo,
                    message: '修改成功',
                    url: '/admin/category'
                })
                return Promise.reject()
            } else {
                return Category.findOne({
                    _id: {
                        $ne: id
                    },
                    name: name
                })
            }

        }
    }).then((sameCategory) => {
        if (sameCategory) {
            res.render('admin/error', {
                userInfo: req.userInfo,
                message: '数据库中已经存在同名分类'
            })
            return Promise.reject()
        } else {
            return Category.update({
                _id: id,
            }, {
                name: name
            })
        }
    }).then(() => {
        res.render('admin/success', {
            userInfo: req.userInfo,
            message: '修改成功',
            url: '/admin/category'
        })
    })
})

router.get('/category/delete', (req, res, next) => {
    var id = req.query.id || ''

    Category.remove({
        _id: id
    }).then(() => {
        res.render('admin/success', {
            userInfo: req.userInfo,
            message: '删除成功',
            url: '/admin/category'
        })
    })
})

router.get('/content', (req, res, next) => {
    let page = Number(req.query.page) || 1,
        limit = 10,
        pages = 0

    Content.count().then((count) => {
        pages = Math.ceil(count / limit)
        page = Math.min(page, pages)
        page = Math.max(page, 1)

        let skip = (page - 1) * limit

        Content.find().sort({
            _id: -1
        }).limit(limit).skip(skip).populate(['category', 'user']).sort({addTime: -1}).then((contents) => {
            res.render('admin/content_index', {
                userInfo: req.userInfo,
                contents,

                count,
                page,
                pages,
                limit
            })
        })

    })
})

router.get('/content/add', (req, res, next) => {

    Category.find().sort({
        _id: -1
    }).then((categories) => {
        res.render('admin/content_add', {
            userInfo: req.userInfo,
            categories
        })
    })

})

router.post('/content/add', (req, res, next) => {
    const body = req.body,
        category = body.category,
        title = body.title,
        description = body.description,
        content = body.content
        console.log(category);
        console.log(title);
    if (!category) {
        res.render('admin/error', {
            userInfo: req.userInfo,
            message: '内容分类不能为空'
        })
        return
    }
    if (!title) {
        res.render('admin/error', {
            userInfo: req.userInfo,
            message: '内容标题不能为空'
        })
        return
    }

    new Content({
        category,
        title,
        user: req.userInfo._id.toString(),
        description,
        content
    }).save().then((rs) => {
        res.render('admin/success', {
            userInfo: req.userInfo,
            message: '内容保存成功',
            url: '/admin/content'
        })
    })

})

router.get('/content/edit', (req, res, next) => {
    const id = req.query.id || ''
    let categories = []
    Category.find().sort({
        _id: 1
    }).then((rs) => {
        categories = rs
        return Content.findOne({
            _id: id
        }).populate('category')
    }).then((content) => {
        if (!content) {
            res.render('admin/error', {
                userInfo: req.userInfo,
                message: '指定内容不存在'
            })
            return Promise.reject()
        } else {
            res.render('admin/content_edit', {
                userInfo: req.userInfo,
                categories,
                content
            })
        }
    })


})

router.post('/content/edit', (req, res) => {
    const id = req.query.id || '',
        body = req.body,
        category = body.category,
        title = body.title,
        description = body.description,
        content = body.content


    if (category == '') {
        res.render('admin/error', {
            userInfo: req.userInfo,
            message: '内容分类不能为空'
        })
        return
    }

    if (title == '') {
        res.render('admin/error', {
            userInfo: req.userInfo,
            message: '内容标题不能为空'
        })
        return
    }

    Content.update({
        _id: id
    }, {
        category,
        title,
        description,
        content
    }).then(() => {
        res.render('admin/success', {
            userInfo: req.userInfo,
            message: '内容保存成功',
            url: '/admin/content'
        })
    })
})

router.get('/content/delete', (req, res) => {
    const id = req.query.id || ''

    Content.remove({
        _id: id
    }).then(() => {
        res.render('admin/success', {
            userInfo: req.userInfo,
            message: '删除成功',
            url: '/admin/content'
        })
    })
})
module.exports = router